package com.fuqi.android.zhongcai.service;

import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

import com.fuqi.android.zhongcai.base.Constants;
import com.fuqi.android.zhongcai.utils.ActivityUtils;
import com.fuqi.android.zhongcai.utils.InstallUtils;


/**
 * Created by juner on 2014/2/24.
 */
public class UpdateVersionService extends Service {

    private DownloadManager dm;
    private long enqueue;
    private String downloadUrl = "";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        if (intent != null) {
            downloadUrl = intent.getStringExtra("download_url");
        }
        if (!downloadUrl.equals("")) {
            startDownload();
        }

        return Service.START_STICKY;
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            InstallUtils.installApp(getApplicationContext(), Constants.UPDATE_APK_STORAGE_LOCATION);

        }
    };


    private void startDownload() {


        dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(
                Uri.parse(downloadUrl));
        request.setMimeType("application/vnd.android.package-archive");
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, Constants.UPDATE_APK_STORAGE_LOCATION);
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterByStatus(DownloadManager.STATUS_RUNNING);
        Cursor cursor = dm.query(query);
        if (cursor.getCount() > 0) {

            ActivityUtils.toast("正在下载最新版本...");

        } else {
            enqueue = dm.enqueue(request);
        }
        Log.i("juner", "juner startDownload enqueue: " + enqueue);
    }
}